<?php

namespace App\Admin\Controllers;

use App\Models\User;
use App\Models\Setting;
use App\Models\AdminUser;
use App\Models\OrderOffline;
use App\Models\ExtendOffline;
use App\Models\Order;
use App\Models\Channel;
use App\Models\Product;
use App\Models\DivideOrder;
use App\Http\Controllers\Controller;
use Encore\Admin\Controllers\HasResourceActions;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Show;
use Encore\Admin\Facades\Admin;
use Hamcrest\Core\Set;
use Illuminate\Support\Facades\Request;
use App\Admin\Extensions\DiscountPay;
use App\Admin\Extensions\DiscountPay2;
use App\Admin\Extensions\GivePay;
use App\Admin\Extensions\WatchRisk;
use App\Admin\Extensions\OfflinePay;
use App\Admin\Extensions\RejudegMent;
use App\Admin\Extensions\PassReJudge;
use App\Admin\Extensions\BlackAdd;
use App\Admin\Extensions\PreCuishou;
use App\Admin\Extensions\GetScore;
use App\Admin\Extensions\Remission;
use App\Admin\Extensions\RejectOrder;
use App\Admin\Extensions\Payquery;
use App\Admin\Extensions\Resign;
use Encore\Admin\Widgets\Table;
use App\Admin\Extensions\FollowList;
use DB;
use App\Admin\Actions\Post\BatchReplicate;
use App\Admin\Extensions\Editpass;
use App\Admin\Extensions\UnbindCard;
use App\Admin\Controllers\CommonController as AdminCommonController;
use App\Admin\Extensions\Sign;
use App\Admin\Extensions\Distribute;
use App\Admin\Extensions\Refuse;
use App\Admin\Extensions\Indicator;

class OrderController extends Controller
{

    use HasResourceActions;

    /**
     * Index interface.
     *
     * @param Content $content
     * @return Content
     */
    public function index(Content $content)
    {
        $uri = explode('/', Request::getRequestUri());
        $url_state = end($uri);
        $url_params = explode('?', $url_state);

        $url_arr = [
            'orders' => '所有申请',
            'all' => '资料齐全',
            'pass' => '待审客户',
            'rejudge' => '签约管理',
            'payrecord' => '已签合同',
            'refuse' => '审核拒绝',
            'payfail' => '打款失败',
            'repayrecord' => '所有回款',
            'todayrepay' => '今日回款',
            'yesterdayrepay' => '昨日回款',
            'afteryesrepay' => '前日回款',
            'today' => '今日到期',
            'tomorrow' => 'T1到期',
            'tomorrowtwo' => 'T2到期',
            'tomorrowthree' => 'T3到期',
            'tomorrowfour' => 'T4到期',
            'tomorrowfive' => 'T5到期',
            'tomorrowsix' => 'T6到期',
            'noreturn' => '优质客户',
            'yesterday' => '所有逾期',
            'yesseven' => '7日内',
            'yesfourteen' => '14日内',
            'yestweentyone' => '21日内',
            'yesmoretweenone' => '21日以上',
            'waitpayrecord' => '签约待确认',
        ];

        return $content
            ->header($url_arr[$url_params[0]])
            ->description('列表')
            ->body($this->grid());

    }

    /**
     * Show interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function show($id, Content $content)
    {
        return $content
            ->header('订单')
            ->description('详情')
            ->body($this->detail($id));
    }

    /**
     * Edit interface.
     *
     * @param mixed $id
     * @param Content $content
     * @return Content
     */
    public function edit($id, Content $content)
    {
        return $content
            ->header('订单')
            ->description('编辑')
            ->body($this->form()->edit($id));
    }

    /**
     * Create interface.
     *
     * @param Content $content
     * @return Content
     */
    public function create(Content $content)
    {
        return $content
            ->header('订单')
            ->description('创建')
            ->body($this->form());
    }

    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        $uri = explode('/', Request::getRequestUri());
        $url_state = end($uri);
        $url_params = explode('?', $url_state);

        $admin_id = Admin::user()->id;
        $allUserids = User::where('admin_id', $admin_id)->pluck('id')->toArray();
        if(Admin::user()->inRoles(['administrator', 'admin'])){
            $where = [];
        }elseif(Admin::user()->inRoles(['financial'])){
            $where = ['financial_id' => Admin::user()->id];
        }elseif(Admin::user()->inRoles(['auditor'])){
            $where = [];
        }elseif(Admin::user()->inRoles(['localcollection'])){
            $where = ['collector_id' => Admin::user()->id];
        }

        $url_arr = [
            'orders' => -100,
            'all' => -100,
            'pass' => 1,
            'rejudge' => 4,
            'payrecord' => 2,
            'refuse' => -1,
            'payfail' => -2,
            'repayrecord' => 3,
            'todayrepay' => 7,
            'yesterdayrepay' => 8,
            'afteryesrepay' => 9,
            'today' => 5,
            'tomorrow' => 6,
            'tomorrowtwo' => 10,
            'tomorrowthree' => 11,
            'tomorrowfour' => 12,
            'tomorrowfive' => 13,
            'tomorrowsix' => 14,
            'noreturn' => 15,
            'yesterday' => -3,
            'yesseven' => 16,
            'yesfourteen' => 17,
            'yestweentyone' => 18,
            'yesmoretweenone' => 19,
            'waitpayrecord' => 20
        ];

        $state = $url_arr[$url_params[0]];
        $grid = new Grid(new Order);

        if ($state == 1) {//待审客户
            $userids = User::where('idcard_ok', 1)->where('alive_ok', 1)->where('carrier_ok', 1)->where('verify_pay_ok', 1)->where('emergency_contact_ok', 1)->pluck('id');
            if(Admin::user()->inRoles(['auditor'])){
                $grid->model()->where(function ($query){
                    $query->where('auditor_id', Admin::user()->id)->where('financial_id', '');
                })->orWhere('auditor_id', '')->whereIn('state', [0, 4])->whereIn('user_id', $userids)->orderBy('pick_date', 'desc')->orderBy('audit_date', 'asc');
            }else{
                $grid->model()->where($where)->whereIn('state', [0, 4])->whereIn('user_id', $userids)->orderBy('pick_date', 'desc')->orderBy('audit_date', 'asc');
            }
        }

        if ($state == -1) {
            if(Admin::user()->inRoles(['auditor'])){
                $grid->model()->where('auditor_id', Admin::user()->id)->where('state', -1)->orderBy('pick_date', 'desc')->orderBy('audit_date', 'asc');
            }else{
                $grid->model()->where($where)->where('state', -1)->orderBy('updated_at', 'desc');
            }
        }

        if ($state == 4) {//签约管理
            $grid->model()->where($where)->whereIn('state', [1])->where('auditor_id', '>', 0)->where('financial_id', '>', 0);
        }
        if ($state == -100) {//已完成的不显示在所有借款里 资料齐全
            $userids = User::where('idcard_ok', 1)->where('carrier_ok', 1)->where('verify_pay_ok', 1)->where('emergency_contact_ok', 1)->pluck('id');
            $grid->model()->where($where)->whereIn('user_id', $userids)->orderBy('id', 'desc');
        }
        if ($state == 5) {
            $start = date('Y-m-d') . ' 00:00:00';
            $end = date('Y-m-d') . ' 23:59:59';
            $divide = DivideOrder::select('order_id')->where('finished_at', ' ')->where('repay_time', '<>', ' ')->where('repay_time', '>', $start)->where('repay_time', '<', $end)->get();
            $divide_arr = [];
            foreach ($divide as $divkey => $divval){
                array_push($divide_arr, $divval->order_id);
            }
            $grid->model()->where($where)->where(function($query) use ($start, $end, $divide_arr){
                $query->where('repayment_at', '>=', $start)->where('repayment_at', '<=', $end)->orWhereIn('id', $divide_arr);
            });
        }
        if ($state == 2) {
            $grid->model()->where($where)->whereIn('state', [2, -3])->orderBy('payment_at', 'desc');
        }

        if ($state == 20) {
            $grid->model()->where($where)->whereIn('state', [5])->orderBy('payment_at', 'desc');
        }

        if ($state == 3) {
            $grid->model()->where($where)->where(function ($query) {
                $query->where('state', 3)->orWhere('extend_time', '<>', ' ');
            })->orderBy('finished_at', 'desc');
        }
        if ($state == 7) {
            //获取今日回款的id集合
            $start = date('Y-m-d'). ' 00:00:00';
            $end = date('Y-m-d'). ' 23:59:59';
            $ExtendOffline = ExtendOffline::select('order_id')->whereBetween('created_at', [$start, $end])->get();
            $OrderOffline = OrderOffline::select('order_id')->whereBetween('created_at', [$start, $end])->whereNotIn('method', ['免减'])->get();
            $ids = [];
            foreach ($ExtendOffline as $exkey => $exval){
                array_push($ids, $exval->order_id);
            }
            foreach ($OrderOffline as $orkey => $orval){
                array_push($ids, $orval->order_id);
            }

            $grid->model()->where($where)->whereIn('id', $ids)->orderBy('finished_at', 'desc');
        }
        if ($state == 8) {
            //获取昨日回款的id集合
            $start = date('Y-m-d', strtotime('-1 day')). ' 00:00:00';
            $end = date('Y-m-d', strtotime('-1 day')). ' 23:59:59';
            $ExtendOffline = ExtendOffline::select('order_id')->whereBetween('created_at', [$start, $end])->get();
            $OrderOffline = OrderOffline::select('order_id')->whereBetween('created_at', [$start, $end])->whereNotIn('method', ['免减'])->get();
            $ids = [];
            foreach ($ExtendOffline as $exkey => $exval){
                array_push($ids, $exval->order_id);
            }
            foreach ($OrderOffline as $orkey => $orval){
                array_push($ids, $orval->order_id);
            }

            $grid->model()->where($where)->whereIn('id', $ids)->orderBy('finished_at', 'desc');
        }
        if ($state == 9) {
            //获取昨日回款的id集合
            $start = date('Y-m-d', strtotime('-2 day')). ' 00:00:00';
            $end = date('Y-m-d', strtotime('-2 day')). ' 23:59:59';
            $ExtendOffline = ExtendOffline::select('order_id')->whereBetween('created_at', [$start, $end])->get();
            $OrderOffline = OrderOffline::select('order_id')->whereBetween('created_at', [$start, $end])->whereNotIn('method', ['免减'])->get();
            $ids = [];
            foreach ($ExtendOffline as $exkey => $exval){
                array_push($ids, $exval->order_id);
            }
            foreach ($OrderOffline as $orkey => $orval){
                array_push($ids, $orval->order_id);
            }

            $grid->model()->where($where)->whereIn('id', $ids)->orderBy('finished_at', 'desc');
        }
        if($state == -2){
            $grid->model()->where($where)->whereIn('state', [-2, 2])->where('payment_at', '=', ' ')->orderBy('pay_out_time', 'desc');
        }
        if($state == -3){
            $grid->model()->where($where)->where(function($query){
                $query->where('finished_at', '')->where('confirm_date', '<>', '')->where('repayment_at', '<>', '')->where('repayment_at', '<', date('Y-m-d').' 00:00:00');
            });
        }
        if($state == 16){
            $grid->model()->where($where)->where(function($query){
                $query->where('finished_at', '')->where('confirm_date', '<>', '')->where('repayment_at', '<>', '')->where('repayment_at', '<', date('Y-m-d').' 00:00:00')->where('repayment_at', '>', date('Y-m-d', strtotime('-7 day')).' 00:00:00');
            });
        }
        if($state == 17){
            $grid->model()->where($where)->where(function($query){
                $query->where('finished_at', '')->where('confirm_date', '<>', '')->where('repayment_at', '<>', '')->where('repayment_at', '<', date('Y-m-d').' 00:00:00')->where('repayment_at', '>', date('Y-m-d', strtotime('-14 day')).' 00:00:00');
            });
        }
        if($state == 18){
            $grid->model()->where($where)->where(function($query){
                $query->where('finished_at', '')->where('confirm_date', '<>', '')->where('repayment_at', '<>', '')->where('repayment_at', '<', date('Y-m-d').' 00:00:00')->where('repayment_at', '>', date('Y-m-d', strtotime('-21 day')).' 00:00:00');
            });
        }
        if($state == 19){
            $grid->model()->where($where)->where(function($query){
                $query->where('finished_at', '')->where('confirm_date', '<>', '')->where('repayment_at', '<>', '')->where('repayment_at', '<', date('Y-m-d', strtotime('-21 day')).' 00:00:00');
            });
        }
        if($state == 6){//T1到期
            $start = date('Y-m-d', strtotime('1 day')) . ' 00:00:00';
            $end = date('Y-m-d', strtotime('1 day')) . ' 23:59:59';
            $divide = DivideOrder::select('order_id')->where('finished_at', ' ')->where('repay_time', '<>', ' ')->where('repay_time', '>', $start)->where('repay_time', '<', $end)->get();
            $divide_arr = [];
            foreach ($divide as $divkey => $divval){
                array_push($divide_arr, $divval->order_id);
            }

            $grid->model()->where($where)->where(function($query) use ($start, $end, $divide_arr){
                $query->where('repayment_at', '>=', $start)->where('repayment_at', '<=', $end)->orWhereIn('id', $divide_arr);
            });
        }
        if($state == 10){//T2到期
            $start = date('Y-m-d', strtotime('2 day')) . ' 00:00:00';
            $end = date('Y-m-d', strtotime('2 day')) . ' 23:59:59';
            $divide = DivideOrder::select('order_id')->where('finished_at', ' ')->where('repay_time', '<>', ' ')->where('repay_time', '>', $start)->where('repay_time', '<', $end)->get();
            $divide_arr = [];
            foreach ($divide as $divkey => $divval){
                array_push($divide_arr, $divval->order_id);
            }

            $grid->model()->where($where)->where(function($query) use ($start, $end, $divide_arr){
                $query->where('repayment_at', '>=', $start)->where('repayment_at', '<=', $end)->orWhereIn('id', $divide_arr);
            });
        }
        if($state == 11){//T3到期
            $start = date('Y-m-d', strtotime('3 day')) . ' 00:00:00';
            $end = date('Y-m-d', strtotime('3 day')) . ' 23:59:59';
            $divide = DivideOrder::select('order_id')->where('finished_at', ' ')->where('repay_time', '<>', ' ')->where('repay_time', '>', $start)->where('repay_time', '<', $end)->get();
            $divide_arr = [];
            foreach ($divide as $divkey => $divval){
                array_push($divide_arr, $divval->order_id);
            }

            $grid->model()->where($where)->where(function($query) use ($start, $end, $divide_arr){
                $query->where('repayment_at', '>=', $start)->where('repayment_at', '<=', $end)->orWhereIn('id', $divide_arr);
            });
        }
        if($state == 12){//T4到期
            $start = date('Y-m-d', strtotime('4 day')) . ' 00:00:00';
            $end = date('Y-m-d', strtotime('4 day')) . ' 23:59:59';
            $divide = DivideOrder::select('order_id')->where('finished_at', ' ')->where('repay_time', '<>', ' ')->where('repay_time', '>', $start)->where('repay_time', '<', $end)->get();
            $divide_arr = [];
            foreach ($divide as $divkey => $divval){
                array_push($divide_arr, $divval->order_id);
            }

            $grid->model()->where($where)->where(function($query) use ($start, $end, $divide_arr){
                $query->where('repayment_at', '>=', $start)->where('repayment_at', '<=', $end)->orWhereIn('id', $divide_arr);
            });
        }
        if($state == 13){//T5到期
            $start = date('Y-m-d', strtotime('5 day')) . ' 00:00:00';
            $end = date('Y-m-d', strtotime('5 day')) . ' 23:59:59';
            $divide = DivideOrder::select('order_id')->where('finished_at', ' ')->where('repay_time', '<>', ' ')->where('repay_time', '>', $start)->where('repay_time', '<', $end)->get();
            $divide_arr = [];
            foreach ($divide as $divkey => $divval){
                array_push($divide_arr, $divval->order_id);
            }

            $grid->model()->where($where)->where(function($query) use ($start, $end, $divide_arr){
                $query->where('repayment_at', '>=', $start)->where('repayment_at', '<=', $end)->orWhereIn('id', $divide_arr);
            });
        }
        if($state == 14){//T6到期
            $start = date('Y-m-d', strtotime('6 day')) . ' 00:00:00';
            $end = date('Y-m-d', strtotime('6 day')) . ' 23:59:59';
            $divide = DivideOrder::select('order_id')->where('finished_at', ' ')->where('repay_time', '<>', ' ')->where('repay_time', '>', $start)->where('repay_time', '<', $end)->get();
            $divide_arr = [];
            foreach ($divide as $divkey => $divval){
                array_push($divide_arr, $divval->order_id);
            }

            $grid->model()->where($where)->where(function($query) use ($start, $end, $divide_arr){
                $query->where('repayment_at', '>=', $start)->where('repayment_at', '<=', $end)->orWhereIn('id', $divide_arr);
            });
        }
        if($state == 15){
            $user = User::select('id')->where('upgradeval', '>', 0)->where('isapply', 1)->where('admin_id', $admin_id)->get();
            $userids = [];
            foreach ($user as $ukey => $uval){
                array_push($userids, $uval->id);
            }
            $orders = Order::whereIn('user_id', $userids)->pluck('id')->toArray();

            $grid->model()->whereIn('id', $orders);
        }

        if(!in_array($state, [-3, 5, 6, 10, 11, 12, 13, 14, 16, 17, 18, 19])){
            $grid->id('Id')->sortable();
            $grid->disableRowSelector();
        }
        $grid->column('channel.name', "推荐人");
        $grid->column('user.verify_name', "姓名")->display(function($val){
            //有逾期则显示红色
            $user_id = $this->user_id;
            $userObj = User::select('positive_number')->where('id', $user_id)->first();
            $positive_number = $userObj['positive_number'];
            $order = Order::where('user_id', $user_id)->get();
            $hasOver = false;
            foreach ($order as $oval){
                if(strtotime($oval->finished_at) > strtotime($oval->repayment_at)){
                    $hasOver = true;
                    break;
                }
            }
            if($hasOver){
                return "<span style='color:red;'>".$val."</span>";
            }
            //多次借款的显示蓝色
            if($this->borrow_count > 0){
                return "<span style='color:blue;'>".$val."</span>";
            }
            //正数的颜色
            if($positive_number == 2){
                return $val."<img src='/newimg/jindun.jpg' style='width: 15px;height: 15px;' alt=''>";
            }
            return $val;
        });
        $grid->column('user.mobile', "手机号");

        if(in_array($state, [2,3,7,8,9,5,6,10,11,12,13,14,15,16,17,18,19,-3,20]) && Admin::user()->inRoles(['administrator'])){
            $grid->column('admin.name', "出借人");
        }

//        if(!in_array($state, [1, 3, 4, 5, 6, -1, -2, 7, 8, 9, 10, 11, 12, 13, 14])){
//            $grid->column('auditor.name', '审核')->display(function ($val) {
//                $audit = [
//                    0 => '人工',
//                    1 => '机审',
//                    2 => '机审'
//                ];
//                $channel = $this->channel;
//                $charge_method = intval($channel['auto_audit_state']);
//                $prefix = $audit[$charge_method];
//                $passtype = $this->passtype;
//                if (in_array($passtype, [0, 3, 4])) {
//                    if (empty($val)) {
//                        return $prefix . '待审';
//                    }
//                    return $val;
//                } else {
//                    if (!empty($val)) {
//                        return $val;
//                    }
//                    return '机审';
//                }
//            });
//        }

        if(in_array($state, [2, 3, -3, -2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, 20])){
            $grid->column('real_fee', '借款本金')->display(function($val){
                return intval($val);
            });
            $grid->column('应收金额')->display(function($val){
                if($this->finished_at){
                    $currTime = $this->finished_at;
                }else{
                    $currTime = date("Y-m-d H:i:s");
                }

                //减免的金额
                $oid = $this->id;
                $allNatialRepayMon =  OrderOffline::selectRaw('sum(money) all_repay_fee')->where('order_id', $oid)->whereIn('method', ['免减'])->first();//回款金额
                $remission_fee = $allNatialRepayMon['all_repay_fee'];

                $payment_at = $this->payment_at;
                //扣费天数
                $difftime = strtotime(substr($currTime, 0, 10)) - strtotime(substr($payment_at, 0, 10));

                $gap_days = intval($difftime / (3600 * 24));//保证当天借当天还款的时候不会有多余的利息

                //计算利息
                $interest_total = ($this->default_interest) / 100 * $this->real_fee * $gap_days / 365;

                #计算总费用
                $total_fee = $this->real_fee + $interest_total;//多次扣款后的总费用
                if($interest_total >= $this->real_fee) $total_fee = 2 * $this->real_fee;

                return round($total_fee - $remission_fee, 2);

            });
        }
//        if(in_array($state, [-3, 16, 17, 18, 19])){
//
//            $grid->cloumn('逾期天数')->display(function(){
//                $current = strtotime(date('Y-m-d').' 23:59:59');
//                $repayment = $this->repayment_at;
//                $repayment_day = strtotime(date('Y-m-d', strtotime($repayment)).' 23:59:59');
//                return ($current - $repayment_day) / 86400;
//            });
//        }
        if(in_array($state, [2, 3, 7, 8, 9, 20])){
            $grid->repayment_fee('回款金额')->display(function($val){
                $oid = $this->id;
                $allNatialRepayMon =  OrderOffline::selectRaw('sum(money) all_repay_fee')->where('order_id', $oid)->whereNotIn('method', ['免减'])->first();//回款金额
                $allNatialExtendMon = ExtendOffline::selectRaw('sum(money) all_extendarr')->where('order_id', $oid)->first();//展期的金额
                $all_repay_arr = $allNatialRepayMon['all_repay_fee'] + $allNatialExtendMon['all_extendarr'];
                return $all_repay_arr;
            })->expand(function ($model) {
                //线下充值
                $comments = $model->orderoffline()->take(100)->get()->map(function ($orderoffline) {
                    return $orderoffline->only(['money', 'method']);
                });
                $offline_array = $comments->toArray();

                return new Table(['还款金额', '还款方式'], $offline_array);
            });
        }

        if(!in_array($state, [2, -2, 3, 5, 6 ,7, 8, 9, 10, 11, 12, 13, 14, -3, 16,17,18,19, 20])){
//            $grid->column('br_score', '准入分')->display(function ($val) {
//                if ($val > 0) {
//                    return intval($val);
//                }
//                return '';
//            })->sortable();
            $grid->column('准入分')->display(function ($val){
                return $this->user->br_score;
            });
        }

//        if(in_array($state, [-100, 1, 4, -1, -3, 15, 16, 17, 18, 19])){
//            $grid->column('act_score', '行为分')->display(function($val){
//                if($val > 0){
//                    return intval($val);
//                }else{
//                    return '';
//                }
//            })->sortable();
//        }
        if(in_array($state, [-1, 4])){
            $grid->risk_score('置信分')->display(function ($val) {
                if ($val > 0) {
                    if($this->is_get_score == 2){
                        return "<span style='color: red;'>".intval($val)."</span>";
                    }
                    return intval($val);
                }
                return '<a href="javascript:"><span data-oid="'.$this->id.'" class="getScore layui-badge layui-bg-gray">获取</span></a>';
            })->sortable();
        }elseif(!in_array($state, [2, 3, -2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, -3, 16,17,18,19,20])){
            $grid->risk_score('置信分')->display(function ($val) {
                if ($val > 0) {
                    if($this->is_get_score == 2){
                        return "<span style='color: red;'>".intval($val)."</span>";
                    }
                    return intval($val);
                }
                return '';
            })->sortable();
        }

        if(in_array($state, [2, -3, 3, -2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,20])){
            $that = $this;
            $grid->column('客户属性')->display(function(){
                $borrow_count = $this->borrow_count;
                $extend_count = count($this->extendoffline);
                $payment_at = $this->payment_at;
                $content = '';
                if($borrow_count >= 0 && $payment_at){
                    $content .= $borrow_count + 1;
                }
                if($extend_count >= 1){
                    $content .= ',Z'. $extend_count;
                }
                if($borrow_count >= 0 && empty($payment_at)){
                    $content = $borrow_count;
                }
                return $content;
            })->expand(function () use ($that){
                //展期记录
                $user_id = $this->user_id;
                $orders = Order::with(['extendoffline' => function($query){
                    $query->orderBy('id', 'desc');
                }])->select('id', 'user_id', 'product_id', 'borrow_count', 'interest', 'default_interest', 'id', 'state', 'real_fee', 'repayment_fee', 'payment_at', 'repayment_at', 'finished_at', 'once_repayment_at')->where('user_id', $user_id)->orderBy('id', 'desc')->get();
                $trade_arr = [];
                foreach ($orders as $orkey => $orval){
                    $oid = $orval->id;
                    $user_state = $orval->state;
                    $finished_at = $orval->finished_at;
                    $payment_at = $orval->payment_at;
                    $repayment_at = $orval->repayment_at;
                    $interest = $orval->interest;
                    $realfee = $orval->real_fee;//借款本金
                    $default_interest = $orval->default_interest;
                    $borrow_count = $orval->borrow_count;
                    $real_fee = $orval->real_fee;
//                    $product_type = $orval->product->product_type;


                    //应还金额
//                    $should_repay_fee = $that->should_paymoney($product_type, $oid, $user_state, $finished_at, $payment_at, $repayment_at, $interest, $realfee, $default_interest);

                    //回款金额
                    $allNatialRepayMon =  OrderOffline::selectRaw('sum(money) all_repay_fee')->where('order_id', $oid)->whereNotIn('method', ['免减'])->first();//回款金额
                    $allNatialExtendMon = ExtendOffline::selectRaw('sum(money) all_extendarr')->where('order_id', $oid)->first();//展期的金额
                    $all_repay_arr = $allNatialRepayMon['all_repay_fee'] + $allNatialExtendMon['all_extendarr'];

                    if($orkey == 0){
                        if(count($orval->extendoffline)){
                            $extend_count = count($orval->extendoffline);
                            foreach ($orval->extendoffline as $exkey => $exval){
                                $trade_arr[] = [
                                    '展'.($extend_count-$exkey), $exval->money, $exval->extime, $exval->method, '', '', '', '', ''
                                ];
                            }
                        }
                    }else{

                        if($borrow_count == 0){
                            $type = '首借';
                        }else{
                            $type = '复借'.$borrow_count;
                        }

                        $trade_arr[] = [
//                            $type, '', '', '', $real_fee, $should_repay_fee, $all_repay_arr, $payment_at, $finished_at
                            $type, '', '', '', $real_fee, 0, $all_repay_arr, $payment_at, $finished_at
                        ];
                    }
                }

                return new Table(['类型', '展期金额', '展期时间', '展期支付方式', '借款本金', '应还金额', '回款金额', '签约时间', '回款时间'], $trade_arr);
            });
        }

        if(in_array($state, [2])){
            $grid->column('状态')->display(function (){
//                $finished_at = $this->finished_at;
//                $extend_time = $this->extend_time;
//                $repayment_at = $this->repayment_at;
//                $current = date('Y-m-d');
//                $today_end = $current. ' 23:59:59';
//                $today_start = $current. ' 00:00:00';

                $state = $this->state;
                $statearr = config('common.order_status');

                return $statearr[$state];

//                if($finished_at){
//                    return "已履约";
//                }
//                if(empty($finished_at) && !empty($extend_time) && strtotime($repayment_at) > strtotime($today_end)){//已展期
//                    return "已展期";
//                }
//                if(empty($finished_at) && !empty($repayment_at) && strtotime($repayment_at) < strtotime($today_start)){//已逾期
//                    return "履约逾期";
//                }
//                return "履约逾期";
            });
        }
        if(in_array($state, [3, 7, 8, 9])){
            $grid->column('状态')->display(function (){
                $finished_at = $this->finished_at;
                $extend_time = $this->extend_time;
                $repayment_at = $this->repayment_at;
                $current = date('Y-m-d');
                $today_end = $current. ' 23:59:59';
                $today_start = $current. ' 00:00:00';

                if($finished_at){
                    return "<button type='button' class='btn btn-xs layui-btn-warm' style='color: #fff'>已还款</button>";
                }
                if(empty($finished_at) && $extend_time && strtotime($repayment_at) > strtotime($today_end)){//已展期
                    return "<button type='button' class='btn btn-xs btn-default'>已展期</button>";
                }
                if(empty($finished_at) && $extend_time && strtotime($repayment_at) < strtotime($today_start)){//已逾期
                    return "<button type='button' class='btn btn-xs btn-default'>已逾期</button>";
                }
                if(empty($finished_at) && $extend_time && strtotime($repayment_at) > strtotime($today_start) && strtotime($repayment_at) < strtotime($today_end)){//今日到期
                    return "<button type='button' class='btn btn-xs btn-default'>今日到期</button>";
                }
            });
        }
        if(in_array($state, [5, 6, 10, 11, 12, 13, 14])){
            $grid->column('状态')->display(function (){
                $finished_at = $this->finished_at;
                $extend_time = $this->extend_time;
                $repayment_at = $this->repayment_at;
                $current = date('Y-m-d');
                $today_end = $current. ' 23:59:59';

                if($finished_at){
                    return "<button type='button' class='btn btn-xs layui-btn-warm' style='color: #fff'>已还款</button>";
                }
                if(empty($finished_at) && $extend_time && strtotime($repayment_at) > strtotime($today_end)){//已展期
                    return "<button type='button' class='btn btn-xs btn-default'>已展期</button>";
                }
                return "<button type='button' class='btn btn-xs btn-default'>未还款</button>";
            });
        }
        if(!in_array($state, [15])){
            $grid->created_at('申请时间')->sortable();
        }
        if(in_array($state, [])){
            $grid->column('拒绝历史')->display(function(){
                $uid = $this->user_id;
                $count = Order::where('user_id', $uid)->where('state', -1)->count();
                return  $count - 1 > 0 ? $count - 1 : '';
            })->expand(function () {
                $uid = $this->user_id;
                $id = $this->id;
                $orders = Order::with(['user', 'product', 'auditor'])->select('id', 'user_id', 'product_id', 'auditor_id','created_at', 'br_score', 'act_score', 'risk_score', 'self_judge_msg')->where('user_id', $uid)->where('id', '<>', $id)->where('state', -1)->get()->toArray();
                $order_arr = [];
                if(count($orders)){
                    foreach ($orders as $arkey => $arval){
                        $order_arr[$arkey]['mobile'] = $arval['user']['mobile'];
                        $order_arr[$arkey]['created'] = $arval['created_at'];
                        $order_arr[$arkey]['product_name'] = $arval['product']['product_name'];
                        $order_arr[$arkey]['auditor'] = $arval['auditor']['username'];
                        $order_arr[$arkey]['br_score'] = $arval['br_score'];
                        $order_arr[$arkey]['act_score'] = $arval['act_score'];
                        $order_arr[$arkey]['risk_score'] = $arval['risk_score'];
                        $order_arr[$arkey]['self_judge_msg'] = $arval['self_judge_msg'];
                    }
                }
                rsort($order_arr);

                return new Table(['手机号', '申请时间', '产品', '审核', '准入分', '行为分', '置信分', '拒绝原因'], $order_arr);
            });
        }
        if(in_array($state, [-2])){
            $grid->column('pay_out_time', "签约时间")->display(function ($val) {
                return !empty($val) ? $val : '--:--:--';
            });
//                ->expand(function ($model) {
//                //线下充值
//                $comments = $model->tradeInfo()->take(100)->get()->map(function ($tradeInfo) {
//                    return $tradeInfo->only(['verify_name', 'out_trade_no', 'bankno', 'created_at']);
//                });
//                $trade_info_array = $comments->toArray();
//                rsort($trade_info_array);
//                return new Table(['账户名', '交易流水号', '银行卡号', '交易时间'], $trade_info_array);
//            })->sortable();

            $grid->column('pay_out_fail', '失败原因');
        }
        if (!in_array($state, [1, 4, -2, -1, 2, 3, -3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 18, 19, -100, 20])) {
            if(!in_array($state, [15])){
                $grid->column('payment_at', "签约时间")->display(function ($val) {
                    return !empty($val) ? $val : '--:--:--';
                })->sortable();
            }

            $grid->column('repayment_at', "履约时间")->display(function ($val) {
                return !empty($val) ? $val : '--:--:--';
            })->sortable();
//            $grid->finished_at('回款时间')->display(function ($val) {
//                return !empty($val) ? $val : '--:--:--';
//            })->expand(function ($model) {
//                //线下充值
//                $comments = $model->orderoffline()->take(100)->get()->map(function ($orderoffline) {
//                    return $orderoffline->only(['money', 'method', 'created_at']);
//                });
//                $offline_array = $comments->toArray();
//
//                return new Table(['还款金额', '还款方式', '时间'], $offline_array);
//            })->sortable();
        }
//        if(in_array($state, [15])){
//            $grid->finished_at('回款时间')->display(function ($val) {
//                return !empty($val) ? $val : '--:--:--';
//            })->expand(function ($model) {
//                //线下充值
//                $comments = $model->orderoffline()->take(100)->get()->map(function ($orderoffline) {
//                    return $orderoffline->only(['money', 'method', 'created_at']);
//                });
//                $offline_array = $comments->toArray();
//
//                return new Table(['还款金额', '还款方式', '时间'], $offline_array);
//            })->sortable();
//        }
        if (in_array($state, [-3, 5, 6, 10, 11, 12, 13, 14, 16, 17, 18, 19])) {
            $grid->column('payment_at', "签约时间")->display(function ($val) {
                return !empty($val) ? $val : '--:--:--';
            })->sortable();
            $grid->column('repayment_at', "履约时间")->display(function ($val) {
                return !empty($val) ? $val : '--:--:--';
            })->sortable();
        }

        if (in_array($state, [2])) {
            $grid->column('payment_at', "签约时间")->display(function ($val) {
                return !empty($val) ? $val : '--:--:--';
            });
//                ->expand(function ($model) {
//                //线下充值
//                $comments = $model->tradeInfo()->take(100)->get()->map(function ($tradeInfo) {
//                    return $tradeInfo->only(['verify_name', 'out_trade_no', 'bankno', 'created_at']);
//                });
//                $trade_info_array = $comments->toArray();
//                rsort($trade_info_array);
//                return new Table(['账户名', '交易流水号', '银行卡号', '交易时间'], $trade_info_array);
//            })->sortable();


            $grid->column('repayment_at', "履约时间")->display(function ($val) {
                $extend_time = $this->extend_time;
                if ($extend_time) {
                    $extend_time = json_decode($extend_time, true);
                    return date('Y-m-d H:i:s', end($extend_time));
                } else {
                    return $val;
                }
            })->sortable();

//            $grid->finished_at('回款时间')->display(function ($val) {
//                return !empty($val) ? $val : '--:--:--';
//            })->sortable();
        }
//        if (in_array($state, [4])) {
//            $grid->self_judge_msg('复审原因');
//        }
        if (in_array($state, [-100, 1])) {
            $statearr = [
                0 => '通过',
                1 => '通过',
                -1 => '签约拒绝',
                5 => '签约待确认',
                2 => '已签约',
                4 => '人工复审',
                3 => '已履约',
                -3 => '履约逾期',
            ];

            $grid->state('状态')->display(function ($state) use ($statearr) {
                return $statearr[$state];
            });
        }
        if (in_array($state, [3, 7, 8, 9])) {
            $grid->column('payment_at', "签约时间")->sortable();
            $grid->column('repayment_at', "履约时间")->sortable();
//            $grid->finished_at('回款时间')->display(function ($val) {
//                return !empty($val) ? $val : '--:--:--';
//            })->sortable();
        }
        if ($state == -1) {
            $grid->column('self_judge_msg', '拒绝原因');
        }

        if(in_array($state, [-100, 2, 3, -1, -3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20])){
            $grid->filter(function ($filter) use ($state) {
                // 禁用id查询框
                $filter->disableIdFilter();

                $filter->column(1 / 2, function ($filter) use($state) {
                    if(!in_array($state, [-100, 3, 7, 8, 9])){
                        $filter->equal('auditor_id', '审核员')->select(AdminUser::all()->pluck('name', 'id'));
                    }

                    $filter->where(function ($query) {
                        $query->whereHas('user', function ($query) {
                            $input = trim($this->input);
                            $query->where('verify_name', '=', "$input");
                        });
                    }, '姓名');

                    if(!in_array($state, [5, 6, 10, 11, 12, 13, 14, 15])){
                        $filter->between('created_at', '申请时间')->date();
                    }
                    if(in_array($state, [3, 7, 8, 9])){
                        $filter->between('payment_at', '签约时间')->date();
                    }
//                    if(in_array($state, [3, 7, 8, 9])){
//                        $filter->between('finished_at', '回款时间')->date();
//                    }
                    if(in_array($state, [5,6,10,11,12,13,14])){
                        $selectArr = [
                            'first' => '首借',
                            'second' => '复借',
                            'extend' => '展期'
                        ];
                    }
                    if(in_array($state, [5,6,10,11,12,13,14])){
                        $filter->where(function ($query) use ($state) {
                            switch ($this->input) {
                                case 'first':
                                    // custom complex query if the 'yes' option is selected
                                    $query->where('borrow_count', 0)->where('payment_at', '<>', '');
                                    break;
                                case 'second':
                                    $query->where('borrow_count', '>', 0)->where('payment_at', '<>', '');
                                    break;
                                case 'extend':
                                    $query->where('extend_time', '<>', '');
                                    break;
                            }
                        }, '客户属性', '客户属性')->select($selectArr);
                    }
                    if(in_array($state, [-100])){
                        $selectArr = [
                            'new' => '新客户',
                            'old' => '老客户'
                        ];
                        $filter->where(function ($query) use ($state) {
                            switch ($this->input) {
                                case 'new':
                                    // custom complex query if the 'yes' option is selected
                                    $query->where('borrow_count', 0);
                                    break;
                                case 'old':
                                    $query->where('borrow_count', '>', 0);
                                    break;
                            }
                        }, '新老客户', '新老客户')->select($selectArr);
                    }
                });

                $filter->column(1 / 2, function ($filter) use ($state) {

                    $filter->equal('channel_id', '渠道')->select(Channel::withTrashed()->get()->pluck('name', 'id'));

                    $filter->where(function ($query) {
                        $query->whereHas('user', function ($query) {
                            $input = trim($this->input);
                            $query->where('mobile', '=', "$input");
                        });
                    }, '手机号');

//                    if(in_array($state, [2, 3, -3, 7, 8, 9, 16, 17, 18, 19])){
//                        $filter->between('repayment_at', '履约时间')->date();
//                    }
                    if(in_array($state, [2, -3, 16, 17, 18, 19])){
                        $filter->between('payment_at', '签约时间')->date();
                    }

                    if(in_array($state, [-1])){
                        $filter->like('self_judge_msg', '拒绝原因');
                    }
                    //状态筛选
                    if(in_array($state, [3, 7, 8, 9])){//回款的状态
                        $selectArr = [
                            'extendpay' => '展期',
                            'repayedpay' => '还款',
                            'remission' => '减免'
                        ];
                    }elseif(in_array($state, [5, 6, 10, 11, 12, 13, 14])){
                        $selectArr = [
                            'extend' => '已展期',
                            'repayed' => '已还款',
                            'norepay' => '未还款',
                        ];
                    }elseif(in_array($state, [-100])){
                        $selectArr = [
                            'reject' => '审核拒绝',
                            'norepay' => '未还款',
                            'extend' => '已展期',
                            'overtime' => '已逾期',
                        ];
                    }elseif(in_array($state, [2])){
                        $selectArr = [
                            'norepay' => '未还款',
                            'repayed' => '已还款',
                            'extend' => '已展期',
                            'overtime' => '已逾期',
                        ];
                    }else{
                        $selectArr = [
                            'first' => '首借',
                            'second' => '复借',
                            'extend' => '已展期',
                            'repayed' => '已还款',
                            'norepay' => '未还款',
                        ];
                    }
                    if(!in_array($state, [-1, -3, 15, 16, 17, 18, 19])){
                        $filter->where(function ($query) use ($state) {
                            $date = date('Y-m-d');
                            $start = $date.' 00:00:00';
                            $end = $date.' 23:59:59';
                            switch ($this->input) {
                                case 'first':
                                    // custom complex query if the 'yes' option is selected
                                    $query->where('borrow_count', 0)->where('payment_at', '<>', '');
                                    break;
                                case 'second':
                                    $query->where('borrow_count', '>', 0)->where('payment_at', '<>', '');
                                    break;
                                case 'repayed':
                                    $divide = DivideOrder::select('order_id')->where('finished_at', '<>', '')->where('repay_time', '<>', '')->get();
                                    $divide_arr = [];
                                    foreach ($divide as $divkey => $divval){
                                        array_push($divide_arr, $divval->order_id);
                                    }
                                    $query->where('finished_at', '<>', '')->where('payment_at', '<>', '')->orWhereIn('id', $divide_arr);
                                    break;
                                case 'norepay':
                                    $divide = DivideOrder::select('order_id')->where('finished_at', '')->where('repay_time', '<>', ' ')->get();
                                    $divide_arr = [];
                                    foreach ($divide as $divkey => $divval){
                                        array_push($divide_arr, $divval->order_id);
                                    }
                                    $query->where('finished_at', '=', '')->where('payment_at', '<>', '')->orWhereIn('id', $divide_arr);
                                    break;
                                case 'extend':
                                    if($state == 3){
                                        $query->where('extend_time', '<>', '');
                                    }else{
                                        $query->where('finished_at', '=', '')->where('extend_time', '<>', '')->where('state', 2);
                                    }
                                    break;
                                case 'reject':
                                    $query->where('state', -1);
                                    break;
                                case 'overtime':
                                    $divide = DivideOrder::select('order_id')->where('finished_at', '')->where('repay_time', '<>', '')->where('repay_time', '<', date('Y-m-d').' 00:00:00')->get();
                                    $divide_arr = [];
                                    foreach ($divide as $divkey => $divval){
                                        array_push($divide_arr, $divval->order_id);
                                    }
                                    $query->where('finished_at', '=', '')->where('repayment_at', '<>', '')->where('repayment_at', '<', $start)->orWhereIn('id', $divide_arr);
                                    break;
                                case 'extendpay':
                                    $query->where('extend_time', '<>', '');
                                    break;
                                case 'repayedpay':
                                    $orderoffline = OrderOffline::select('id', 'order_id')->whereNotIn('method', ['免减'])->get();
                                    $orderids = [];
                                    foreach ($orderoffline as $orkey => $orval){
                                        array_push($orderids, $orval->order_id);
                                    }
                                    $query->whereIn('id', $orderids)->where('finished_at', '<>', '');
                                    break;
                                case 'remission':
                                    $orderoffline = OrderOffline::select('id', 'order_id')->whereIn('method', ['免减'])->get();
                                    $orderids = [];
                                    foreach ($orderoffline as $orkey => $orval){
                                        array_push($orderids, $orval->order_id);
                                    }
                                    $query->whereIn('id', $orderids)->where('finished_at', '<>', '');
                                    break;
                            }
                        }, '状态', '状态')->select($selectArr);
                    }
                });
            });
        }
        if(in_array($state, [1, 4, -2])){
            $grid->disableFilter();
        }
        if (in_array($state, [4])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $name = $actions->row->user['verify_name'];

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $oid = $actions->getKey();
                $mobile = $actions->row->user['mobile'];
                $merchant = $row->tenant_id;

                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
                $actions->append(new Sign($oid));
//                $actions->append(new RejudegMent($oid, $name));
                $actions->append(new GetScore($oid));
            });
        }

        if (in_array($state, [20])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $name = $actions->row->user['verify_name'];

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $oid = $actions->getKey();
                $mobile = $actions->row->user['mobile'];
                $merchant = $row->tenant_id;

                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
//                $actions->append(new RejudegMent($oid, $name));
//                $actions->append(new GetScore($oid));
            });
        }

        if (in_array($state, [-1])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $id = $actions->getKey();
                $mobile = $actions->row->user['mobile'];
                $name = $actions->row->user['verify_name'];

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $oid = $actions->getKey();
                $merchant = $row->tenant_id;

                $auditor_id = $row->auditor_id;
                $financial_id = $row->financial_id;
                $state = $row->state;

                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
//                $actions->append(new Sign($oid));
                $actions->append(new WatchRisk('', '', false, $mobile, '', '', $merchant));
                $actions->append(new GetScore($id));
                $actions->append(new Indicator($oid, $name, $auditor_id, $financial_id, $state));
            });
        }
        if (in_array($state, [1])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $id = $actions->getKey();
                $name = $actions->row->user['verify_name'];
                $passtype = $actions->row->passtype;
                $is_black = $actions->row->is_black;

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $oid = $actions->getKey();
                $mobile = $actions->row->user['mobile'];
                $merchant = $row->tenant_id;
                $auditor_id = $row->auditor_id;
                $financial_id = $row->financial_id;
                $state = $row->state;

                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
                $actions->append(new WatchRisk('', '', false, $mobile, '', '', $merchant));
//                $actions->append(new Sign($oid));
                if ($is_black == 1) {
//                    $actions->append(new BlackAdd($oid));
                }
                //添加分配和拒绝按钮
//                $actions->append(new Distribute($uid));
//                $actions->append(new Refuse($oid, $name));
                $actions->append(new Indicator($oid, $name, $auditor_id, $financial_id, $state));
            });
        }
        if (in_array($state, [3, 7, 8, 9])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $row = $actions->row;
                $uid = $row->user_id;
                $oid = $row->id;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $mobile = $actions->row->user['mobile'];
                $merchant = $row->tenant_id;
                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
                $actions->append(new Resign($uid, '', $oid));
            });
        }

        if (in_array($state, [2])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $id = $actions->getKey();
                $mobile = $actions->row->user['mobile'];
                // 添加操作
                $oid = $actions->getKey();
                $title = $actions->row->user['verify_name'];
                $finished_at = $actions->row->finished_at;
                $row = $actions->row;
                $uid = $row->user_id;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $product_type = $actions->row->product['product_type'];
                $merchant = $row->tenant_id;

                if(!$finished_at){
                    $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
                    $actions->append(new OfflinePay($oid, $title, $product_type));
//                    $actions->append(new DiscountPay2($id, $product_type, $title));
                    $actions->append(new Remission($id, $product_type));
//                    $actions->append(new Payquery($oid, $title));
                }
            });
        }
        if (in_array($state, [-3, 16, 17, 18, 19])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $id = $actions->getKey();
                $mobile = $actions->row->user['mobile'];
                // 添加操作
                $oid = $actions->getKey();
                $is_black = $actions->row->is_black;
                $title = $actions->row->user['verify_name'];
                $repayment_state = $actions->row->repayment_state;

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $product_type = $actions->row->product['product_type'];
                $merchant = $row->tenant_id;
                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
                $actions->append(new OfflinePay($oid, $title, $product_type));
//                $actions->append(new DiscountPay2($id, $product_type, $title));
                $has_auth = Admin::user()->inRoles(['admin', 'administrator']);
                if($has_auth){
                    if(in_array($repayment_state, [0,1])){
                        $actions->append(new PreCuishou($title, $oid, 1));//提前委外催收
                    }else{
                        $actions->append(new PreCuishou($title, $oid, 2));//提前委外催收已催收
                    }
                }
                $actions->append(new FollowList($oid, $title));
                if ($is_black == 1) {
//                    $actions->append(new BlackAdd($oid));
                }
            });
        }

        if (in_array($state, [-2])) {
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $id = $actions->getKey();
                $mobile = $actions->row->user['mobile'];
                $title = $actions->row->user['verify_name'];

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $oid = $actions->getKey();
                $merchant = $row->tenant_id;

                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
                $actions->append(new GivePay($id));
//                $actions->append(new Payquery($oid, $title));
            });
        }
        if(in_array($state, [15])){
            $grid->actions(function ($actions) {
                $actions->disableDelete();
                $actions->disableView();
                $actions->disableEdit();
                $id = $actions->getKey();
                $mobile = $actions->row->user['mobile'];

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $oid = $actions->getKey();
                $merchant = $row->tenant_id;

                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
            });
        }
        if ($state == -100) {
            $grid->actions(function ($actions) {
                $actions->disableView();
                $actions->disableDelete();
                $actions->disableEdit();
                $mobile = $actions->row->user['mobile'];
                $is_black = $actions->row->is_black;

                $row = $actions->row;
                $order_no = $row->out_trade_no;
                $id_no = $row->user['verify_idcard_no'];
                $uid = $row->user_id;
                $oid = $actions->getKey();
                $verify_name = $row->user['verify_name'];
                $merchant = $row->tenant_id;
                $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));
                $is_adminstor = Admin::user()->inRoles(['administrator']);
                if($is_adminstor){
//                    $actions->append('<a href="/admin/orders/' . $oid . '/edit" class="layui-btn layui-btn-xs">编辑</a> ');
                }
//                $actions->append(new Sign($oid));
                $is_admin = Admin::user()->inRoles(['admin']);
                if($is_adminstor || $is_admin){
                    $actions->append(new Editpass($uid, $verify_name));
//                    $actions->append(new UnbindCard($uid, $verify_name));
                }
                if ($is_black == 1) {
//                    $actions->append(new BlackAdd($oid));
                }
            });
        }
        if (in_array($state, [5, 6, 10, 11, 12, 13, 14])) {
            $has_auth = Admin::user()->inRoles(['admin', 'administrator', 'collector', 'localcollector', 'today']);
            if($has_auth){
                $grid->actions(function ($actions){
                    $actions->disableDelete();
                    $actions->disableView();
                    $actions->disableEdit();
                    $oid = $actions->getKey();
                    $title = $actions->row->user['verify_name'];
                    $repayment_state = $actions->row->repayment_state;
                    $is_black = $actions->row->is_black;

                    $row = $actions->row;
                    $uid = $row->user_id;
                    $order_no = $row->out_trade_no;
                    $id_no = $row->user['verify_idcard_no'];
                    $mobile = $actions->row->user['mobile'];
                    $product_type = $actions->row->product['product_type'];
                    $merchant = $row->tenant_id;

                    $actions->append(new WatchRisk($uid, $oid, true, $mobile, $order_no, $id_no, $merchant));

                    if(in_array($repayment_state, [0,1])){
                        $actions->append(new PreCuishou($title, $oid, 1));//提前委外催收
                    }else{
                        $actions->append(new PreCuishou($title, $oid, 2));//提前委外催收
                    }
                    $actions->append(new OfflinePay($oid, $title, $product_type));
//                    $actions->append(new DiscountPay2($oid, $product_type, $title));
                    $actions->append(new Remission($oid, $product_type));
                    $actions->append(new FollowList($oid, $title));
                    if ($is_black == 1) {
//                        $actions->append(new BlackAdd($oid));
                    }
                });
            }else{
                $grid->disableActions();
            }
        }
        if(in_array($state, [5])){
            $grid->footer(function ($query) {
                // 查询出已支付状态的订单总金额
                $data = Order::select(DB::raw("count(id) as rep_count"))->where('state', 3)->where('finished_at', '<>', '')->whereBetween('repayment_at', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59'])->first();
                $allOrders = Order::select(DB::raw("count(id) as all_rep_count"))->whereBetween('repayment_at', [date('Y-m-d') . ' 00:00:00', date('Y-m-d') . ' 23:59:59'])->first();
                $notRepayCnt = $allOrders['all_rep_count'] - $data['rep_count'];
                return "<div style='padding: 10px;'><span style='color: deepskyblue;' class='glyphicon glyphicon-signal'></span>还款统计 ：总数<span style='color: red;'>$allOrders->all_rep_count</span>笔-还款成功<span style='color: red;'>$data->rep_count</span>笔-未还<span style='color: red;'>$notRepayCnt</span>笔</div>";
            });
        }
//        $grid->batchActions(function ($batch) {
//            $batch->add(new BatchReplicate());
//            $batch->disableDelete();
//        });

        $grid->disableCreateButton();
        $grid->disableExport();

        return $grid;
    }

    /**
     * Make a show builder.
     *
     * @param mixed $id
     * @return Show
     */
    protected function detail($id)
    {

    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Order);
        $statearr = [
            1 => '审核通过',
            2 => '已打款',
            3 => '已还款',
            -1 => '审核不通过',
            -2 => '打款失败',
//            -3 => '还款失败'
        ];
        $form->display('user.verify_name', '用户姓名');
        $form->select('state', "订单状态")->options($statearr);
        $form->text('verify_text', '处理意见')->rules('required|min:10', [
            'required' => '处理意见必须填写',
            'min' => '处理意见字数必须大于10',
        ]);
//        $form->id('id','ID');
        $form->display('out_trade_no', '订单编号');
        $form->display('total_fee', '额度');
        $form->display('days', '期数(天)');
        $form->display('change_fee', '服务费');
        $form->display('real_fee', '到账金额');
        $form->display('repayment_fee', '已还款金额');

        $form->display('created_at', '申请时间');
        $form->display('audited_at', '审核时间');
        $form->display('payment_at', '签约时间');
//        $form->datetime('repayment_at','履约时间');


        $form->display('repayment_count', '扣款次数');

        //$form->text('state','状态');
        $form->display('error_msg', '状态');


        $form->saved(function (Form $form) {
            $auditor = Admin::user()->id;
            $uid = $form->model()->user->id;
            $auditor_name = $form->model()->user->username;
            $mobile = $form->model()->user->mobile;
            $id = $form->model()->id;
            $payment_at = $form->model()->payment_at;
            $finished_at = $form->model()->finished_at;
            $state = $form->model()->state;
            $out_trade_no = $form->model()->out_trade_no;
            if ($state == 1) {
                @file_put_contents('../storage/logs/admin_change_user_state.log', 'date=' . date('Y-m-d H:i:s') . '||act=' . $auditor_name . '_change_' . $id . '_state_to_1'.PHP_EOL, FILE_APPEND);
                if(empty($payment_at)){
                    $form->model()->passtype = 3;//人工的审核通过
                    $form->model()->audited_at = date('Y-m-d H:i:s');
                    $form->model()->error_msg .= '|人工审核通过';
                    $user = User::where('id', $uid)->first();
                    $user->isapply = 2;//改成已申请
                    $user->save();
                    //日志
                    $common_obj = new AdminCommonController();
                    $detail = '对客户'.$mobile.'进行了编辑操作，更改状态为 审核通过';
                    $common_obj->black_logoperation($detail);
                    //如果是分期产品，给分期产品分配时间
                    $product_type = $form->model()->product['product_type'];
                    if($product_type == 2){
                        $divide_obj = DivideOrder::where('order_id', $id)->get();
                        foreach ($divide_obj as $divkey => $divval){
                            $divval->state = 1;
                            $divval->save();
                        }
                    }
                }elseif(!empty($finished_at)){
                    $form->model()->state = 3;
                    $form->model()->error_msg .= '|人工审核通过但已还款';
                }else{
                    $form->model()->state = 2;
                    $form->model()->error_msg .= '|人工审核通过但已打款';
                }
            }
            if ($state == -1) {
                @file_put_contents('../storage/logs/admin_change_user_state.log', 'date=' . date('Y-m-d H:i:s') . '||act=' . $auditor_name . '_change_' . $id . '_state_to_-1'.PHP_EOL, FILE_APPEND);
                if(empty($payment_at)){
                    $form->model()->passtype = 4;//人工的审核拒绝
                    $form->model()->audited_at = date('Y-m-d H:i:s');
                    $form->model()->error_msg .= '|人工审核拒绝';
                    $form->model()->self_judge_msg = '人工编辑审核拒绝';
                    $user = User::where('id', $uid)->first();
                    $user->isapply = 2;//改成已申请
                    $user->save();
                    //记录日志
                    $common_obj = new AdminCommonController();
                    $detail = '对客户'.$mobile.'进行了编辑操作，更改状态为 审核拒绝';
                    $common_obj->black_logoperation($detail);
                }elseif(!empty($finished_at)){
                    $form->model()->state = 3;
                    $form->model()->error_msg .= '|人工审核拒绝但已还款';
                }else{
                    $form->model()->state = 2;
                    $form->model()->error_msg .= '|人工审核拒绝但已打款';
                }
            }
            if ($state == 2) {
                @file_put_contents('../storage/logs/admin_change_user_state.log', 'date=' . date('Y-m-d H:i:s') . '||act=' . $auditor_name . '_change_' . $id . '_state_to_2'.PHP_EOL, FILE_APPEND);
                if(empty($payment_at)){
                    $repay_days = $form->model()->days;
                    $now_time = time();
                    $form->model()->passtype = 13;//人工的已打款
                    $form->model()->payment_at = date('Y-m-d H:i:s');
                    $form->model()->repayment_at = date('Y-m-d H:i:s', $now_time + $repay_days * 86400);
                    $form->model()->audited_at = date('Y-m-d H:i:s');
                    $form->model()->finished_at = '';
                    $form->model()->error_msg .= '|人工审核成已打款';
                    $user = User::where('id', $uid)->first();
                    $user->finished_time = '';
                    $user->isapply = 2;//改成已申请
                    $user->save();
                    //记录日志
                    $common_obj = new AdminCommonController();
                    $detail = '对客户'.$mobile.'进行了编辑操作，更改状态为 打款成功';
                    $common_obj->black_logoperation($detail);
                    //如果是分期产品，给分期产品分配时间
                    $product_type = $form->model()->product['product_type'];
                    if($product_type == 2){
                        $divide_obj = DivideOrder::where('order_id', $id)->get();
                        foreach ($divide_obj as $divkey => $divval){
                            $repay_time = $now_time + 86400 * $divval->divide_day * $divval->divide_num;
                            $divval->pay_time = date('Y-m-d H:i:s', $now_time);
                            $divval->repay_time = date('Y-m-d H:i:s', $repay_time);
                            $divval->state = 2;
                            $divval->save();
                        }
                    }
                }elseif(!empty($finished_at)){
                    $form->model()->state = 3;//如果打款成功，还是打款成功的状态
                    $form->model()->error_msg .= '|人工审核成已打款但已还款';
                }
            }
            //如果状态改成已还款，那么user和order表的时间要改变
            if ($state == 3) {
                @file_put_contents('../storage/logs/admin_change_user_state.log', 'date=' . date('Y-m-d H:i:s') . '||act=' . $auditor_name . '_change_' . $id . '_state_to_3'.PHP_EOL, FILE_APPEND);
                if(empty($payment_at)){
                    $form->model()->state = -2;//限定成打款失败
                    $form->model()->error_msg .= '|人工审核成已还款但未打款';
                }elseif(empty($finished_at)){
                    $form->model()->finished_at = date('Y-m-d H:i:s');
                    $form->model()->error_msg .= '|人工审核成已还款';
                    $user = User::where('id', $uid)->first();
                    $user->finished_time = date('Y-m-d H:i:s');
                    $user->isapply = 1;//改成未申请
                    $user->upgradeval = $user->upgradeval + 1;//用于提额
                    $user->save();
                    //如果是分期产品，给分期产品分配时间
                    $product_type = $form->model()->product['product_type'];
                    if($product_type == 2){
                        $divide_obj = DivideOrder::where('order_id', $id)->get();
                        foreach ($divide_obj as $divkey => $divval){
                            $divval->state = 3;
                            $divval->save();
                        }
                    }
                }
            }
            //还款失败，一般在催收里改状态，主要是为了测试用
            if ($state == -3) {
                @file_put_contents('../storage/logs/admin_change_user_state.log', 'date=' . date('Y-m-d H:i:s') . '||act=' . $auditor_name . '_change_' . $id . '_state_to_-3'.PHP_EOL, FILE_APPEND);
                if(empty($payment_at)){
                    $form->model()->state = -2;//限定成打款失败
                    $form->model()->error_msg .= '|人工审核成还款失败但未打款';
                }elseif(!empty($finished_at)){
                    $form->model()->state = 3;//打过款了就还是打款成功
                    $form->model()->error_msg .= '|人工审核成还款失败但已还款';
                }else{
                    $form->model()->error_msg .= '|人工审核成还款失败';
                    $user = User::where('id', $uid)->first();
                    $user->finished_time = date('Y-m-d H:i:s');
                    $user->isapply = 1;//改成未申请
                    $user->save();
                    //如果是分期产品，给分期产品分配时间
                    $product_type = $form->model()->product['product_type'];
                    if($product_type == 2){
                        $divide_obj = DivideOrder::where('order_id', $id)->get();
                        foreach ($divide_obj as $divkey => $divval){
                            $divval->state = -3;
                            $divval->save();
                        }
                    }
                }
            }
            $form->model()->auditor_id = $auditor;
            $form->model()->save();
        });
        $form->footer(function ($footer) {

            // 去掉`重置`按钮
            $footer->disableReset();

            // 去掉`提交`按钮
//            $footer->disableSubmit();

            // 去掉`查看`checkbox
            $footer->disableViewCheck();

            // 去掉`继续编辑`checkbox
            $footer->disableEditingCheck();

            // 去掉`继续创建`checkbox
            $footer->disableCreatingCheck();

        });
        $form->tools(function (Form\Tools $tools) {

            // 去掉`删除`按钮
            $tools->disableDelete();

            // 去掉`查看`按钮
            $tools->disableView();

            // 添加一个按钮, 参数可以是字符串, 或者实现了Renderable或Htmlable接口的对象实例
            //$tools->add('<a class="btn btn-sm btn-danger"><i class="fa fa-trash"></i>&nbsp;&nbsp;delete</a>');
        });
        return $form;
    }
    //获得应还金额
    protected function should_paymoney($product_type, $oid, $user_state, $finished_at, $payment_at, $repayment_at, $interest, $realfee, $default_interest){

        if($user_state >= 2){
            if($finished_at){
                $currTime = $finished_at;
            }else{
                $currTime = date("Y-m-d H:i:s");
            }
        }else{
            $currTime = '';
        }
        //减免的金额
        $allNatialRepayMon =  OrderOffline::selectRaw('sum(money) all_repay_fee')->where('order_id', $oid)->whereIn('method', ['免减'])->first();//回款金额
        $remission_fee = $allNatialRepayMon['all_repay_fee'];

        if($product_type == 1){
            $payment_at = $payment_at;
            $repayment_at = $repayment_at;
            //扣费天数
            $difftime = strtotime(substr($currTime, 0, 10)) - strtotime(substr($payment_at, 0, 10));

            $gap_days = intval($difftime / (3600 * 24));//保证当天借当天还款的时候不会有多余的利息

            //计算利息
            $interest_total = ($interest) * ($realfee) * ($gap_days) / 10000;

            #计算罚息
            $default_interest_total = 0;
            if (!empty($repayment_at) && strtotime(substr($currTime, 0, 10)) - strtotime(substr($repayment_at, 0, 10)) > 0) {
                $gap_days = intval((strtotime(substr($currTime, 0, 10)) - strtotime(substr($repayment_at, 0, 10)))/86400);
                $default_interest_total = $default_interest * $gap_days;
            }
            if($default_interest_total > $realfee){
                $default_interest_total = $realfee;
            }

            #计算总费用
            $total_fee = $realfee + $interest_total + $default_interest_total;//多次扣款后的总费用
            return round($total_fee/100 - $remission_fee, 2);
        }elseif($product_type == 2){
            $divide_orders = DivideOrder::where('order_id', $oid)->get();
            $should_repaymon = 0;
            foreach ($divide_orders as $dikey => $dival){
                #计算罚息
                $repayment_at = $dival->repay_time;
                $default_interest_total = 0;
                $real_fee = $dival->real_fee;
                if (!empty($repayment_at) && strtotime(substr($currTime, 0, 10)) - strtotime(substr($repayment_at, 0, 10)) > 0) {
                    $gap_days = intval((strtotime(substr($currTime, 0, 10)) - strtotime(substr($repayment_at, 0, 10)))/86400);
                    $default_interest_total = $default_interest * $gap_days;
                }
                if($default_interest_total > $real_fee){
                    $default_interest_total = $real_fee;
                }
                $should_repaymon += $default_interest_total;
            }

            $total_fee = $realfee + $should_repaymon;//多次扣款后的总费用
            return round($total_fee/100 - $remission_fee, 2);
        }
    }
}
